package com.chenliang.sc.interceptor;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @program: springcase
 * @description: 拦截器的实现
 * @author: 陈亮
 * @create: 2022-06-09 18:25
 */
@Configuration
@ConditionalOnProperty(
        prefix = "config",
        name = {"interceptor.open"},
        havingValue = "true",
        matchIfMissing = false
)
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
    
    
    
    
    @Bean
    public MyInterceptor01 myInterceptor01(){
        return new MyInterceptor01();
    }
    @Bean
    public MyInterceptor02 myInterceptor02(){
        return new MyInterceptor02();
    }




    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        /**
         * 多个拦截器组成拦截器链
         * addPathPatterns 用于添加拦截规则 /** 表示拦截所有
         * excludePathPatterns 用户排除拦截 添加了表示路径拦截不到
         * registry.addInterceptor(拦截器)的顺序决定拦截器执行的顺序
         */


        /**
         * addInterceptors()里直接registry.addInterceptor(new 自定义拦截器) 拦截器也是生效的. 这里需要额外多次一举. @Bean呢?
         * 因为如果不是这样写, 我们在自定义拦截器类里处理业务的时候,假如需要自动注入一些对象,这些对象是null, 需要这样写才会成功注入对象
         * 解决方式2种:
         * 第一：　拦截器类添加＠Component注解.在这里@Autwire注入拦截器, 注入的拦截器直接registry.addInterceptor
         * 第二:　　拦截器不需要添加任何注解，直接在这里如下
         **/
//        registry.addInterceptor(new MyInterceptor01()).addPathPatterns("/**")
//                .excludePathPatterns("/user/test2");
//        registry.addInterceptor(new MyInterceptor02()).addPathPatterns("/**")
//                .excludePathPatterns("/user/test2", "/user/test3");
//        super.addInterceptors(registry);
        registry.addInterceptor(myInterceptor01()).addPathPatterns("/**")
                .excludePathPatterns("/user/test2");
        registry.addInterceptor(myInterceptor02()).addPathPatterns("/**")
                .excludePathPatterns("/user/test2", "/user/test3");
        super.addInterceptors(registry);
    }

    /**
     * 仿佛在执行一个环
     * MyInterceptor 01 的preHandle
     * MyInterceptor 02 的preHandle 
     *
     * 执行到controller
     *
     * MyInterceptor 02 的postHandle
     * MyInterceptor 01 的postHandle
     *
     * MyInterceptor 02 的afterCompletion
     * MyInterceptor 01 的afterCompletion
     */
}
